package com.autotest.nore.controller;

import com.autotest.nore.common.exception.TokenEmptyException;
import com.autotest.nore.domain.Database;
import com.autotest.nore.dto.DatabaseDTO;
import com.autotest.nore.service.DatabaseService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.List;


@RestController
@RequestMapping("/autotest/database")
public class DatabaseController {

    @Autowired
    private DatabaseService databaseService;

    @PostMapping("/save")
    public void saveDatabase(@RequestBody DatabaseDTO database, HttpServletRequest request) {
        HttpSession session = request.getSession(false); // 获取会话，如果不存在则返回null
        if (session == null || session.getAttribute("userName") == null) {
            throw new TokenEmptyException("用户未登录，请重新登录");
        }
        String userName = session.getAttribute("userName").toString();
        database.setUpdateUser(userName);
        databaseService.saveDatabase(database);
    }

    @PostMapping("/delete")
    public void deleteEnvironment(@RequestBody Database database) {
        databaseService.deleteDatabase(database);
    }

    @GetMapping("/name/list/{projectId}")
    public List<String> getDatabaseNameList(@PathVariable String projectId) {
        return databaseService.getDatabaseNameList(projectId);
    }

    @GetMapping("/list/{environmentId}")
    public List<DatabaseDTO> getDatabaseList(@PathVariable String environmentId) {
        return databaseService.getDatabaseList(environmentId);
    }

}
